package im.zego.zimexample.ui.room;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;

import androidx.annotation.Nullable;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

import im.zego.zim.ZIM;
import im.zego.zim.callback.ZIMMessageQueriedCallback;
import im.zego.zim.callback.ZIMMessageSentCallback;
import im.zego.zim.callback.ZIMRoomOnlineMemberCountQueriedCallback;
import im.zego.zim.entity.ZIMCustomMessage;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.entity.ZIMMessage;
import im.zego.zim.entity.ZIMTextMessage;
import im.zego.zim.enums.ZIMErrorCode;
import im.zego.zim.enums.ZIMMessagePriority;
import im.zego.zimexample.R;
import im.zego.zimexample.SDKManager;
import im.zego.zimexample.emus.ChatItemType;
import im.zego.zimexample.emus.ChatType;
import im.zego.zimexample.entity.MessageInfo;
import im.zego.zimexample.ui.base.ZIMSessionBashActivity;


public class ZIMRoomSessionActivity extends ZIMSessionBashActivity implements ZIMMessageSentCallback, ZIMMessageQueriedCallback, SDKManager.OnReceiveRoomMessage {


    public static void actionStart(Activity mainActivity, String fromUserID, String roomID) {
        Intent intent = new Intent(mainActivity, ZIMRoomSessionActivity.class);
        intent.putExtra("fromUserID", fromUserID);
        intent.putExtra("roomID", roomID);
        mainActivity.startActivityForResult(intent, 0);
    }

    String TAG = "ZIMRoomSessionActivity";
    private String roomID, fromUserID;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        roomID = getIntent().getStringExtra("roomID");
        fromUserID = getIntent().getStringExtra("fromUserID");
        setTitle(roomID);
        // 查询房间人数
        SDKManager.sharedInstance().queryRoomOnlineMemberCount(roomID, new ZIMRoomOnlineMemberCountQueriedCallback() {
            @SuppressLint("DefaultLocale")
            @Override
            public void onRoomOnlineMemberCountQueried(int i, ZIMError zimErrorCode) {
                setTitle(String.format("%s (%d)", roomID, i));
            }
        });

        SDKManager.sharedInstance().addReceiveRoomMessageCallback(this);

    }

    public void sendMsg(String content) {
        if ("".equals(content.replace(" ", ""))) {
            Toast.makeText(ZIMRoomSessionActivity.this, "Please enter valid content", Toast.LENGTH_LONG).show();
            return;
        }

        CheckBox checkBox = findViewById(R.id.isBinary);
        ZIMMessage zimMessage;
        if (checkBox.isChecked()) {
            ZIMCustomMessage zimCustomMessage = new ZIMCustomMessage();
            zimCustomMessage.message = content.getBytes(StandardCharsets.UTF_8);
            zimCustomMessage.priority = ZIMMessagePriority.LOW;
            zimMessage = zimCustomMessage;
        } else {
            ZIMTextMessage zimTextMessage = new ZIMTextMessage();
            zimTextMessage.message = content;
            zimTextMessage.priority = ZIMMessagePriority.LOW;
            zimMessage = zimTextMessage;
        }
        SDKManager.sharedInstance().sendRoomMsg(zimMessage, roomID, this);

        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setContent(checkBox.isChecked() ? "binary: " + content : content);
        messageInfo.setTime(System.currentTimeMillis());
        messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_RIGHT.value);
        messageInfo.setUserID(fromUserID);
        addMsg(messageInfo);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void finish() {
        super.finish();
        SDKManager.sharedInstance().logoutRoom(roomID);
        SDKManager.sharedInstance().removeReceiveRoomMessageCallback(this);
    }

    @Override
    public void onMessageSent(ZIMMessage zimMessage, ZIMError zimError) {
        if (zimError.code != ZIMErrorCode.SUCCESS) {
            Toast.makeText(this, "Failed to send message error: " + zimError.code.name(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onMessageQueried(ArrayList<ZIMMessage> arrayList, ZIMError zimError) {
        for (ZIMMessage message : arrayList) {
            if (message instanceof ZIMTextMessage) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent(((ZIMTextMessage) message).message);
                messageInfo.setMessageID(message.messageID);
                messageInfo.setTime(message.timestamp);
                if (message.userID.equals(fromUserID)) {
                    messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_RIGHT.value);
                } else {
                    messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_LEFT.value);
                }
                addMsg(messageInfo);
            }

        }
    }

    @Override
    protected ChatType getChatType() {
        return ChatType.CHAT_TYPE_ROOM;
    }

    @Override
    public void queryMember(View view) {
        super.queryMember(view);
        ZIMRoomMemberActivity.actionStart(this, roomID);
    }

    @Override
    public void onReceiveRoomMessage(ZIM zim, ArrayList<ZIMMessage> messageList, String fromRoomID) {
        for (ZIMMessage message : messageList) {
            if (message instanceof ZIMTextMessage && fromRoomID.equals(roomID)) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent(((ZIMTextMessage) message).message);
                messageInfo.setMessageID(message.messageID);
                messageInfo.setUserID(message.userID);
                messageInfo.setTime(message.timestamp);
                messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_LEFT.value);
                addMsg(messageInfo);

            }
            if (message instanceof ZIMCustomMessage && fromRoomID.equals(roomID)) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent(new String(((ZIMCustomMessage) message).message, StandardCharsets.UTF_8));
                messageInfo.setMessageID(message.messageID);
                messageInfo.setUserID(message.userID);
                messageInfo.setTime(message.timestamp);
                messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_LEFT.value);
                addMsg(messageInfo);
            }
        }
    }

}
